package kr.hyunist.calendarproject.Fragment;

import java.util.ArrayList;
import java.util.Calendar;

import kr.hyunist.calendarproject.R;
import kr.hyunist.calendarproject.Adapter.MonthCalendarAdapter;
import kr.hyunist.calendarproject.Adapter.TodayListAdapter;
import kr.hyunist.calendarproject.DAO.DAO;
import kr.hyunist.calendarproject.DTO.DayInfo;
import kr.hyunist.calendarproject.DTO.DayViewHolde;
import kr.hyunist.calendarproject.DTO.MyItem;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MonthCalendar extends Fragment {
	final static String TAG = "DATE";
	public static String currentDate;
	TodayListAdapter tlAdapter;
	MonthCalendarAdapter mCalendarAdapter;
	ArrayList<DayInfo> mDayList;
	ArrayList<MyItem> arList;
	int SUNDAY = 1;
	TextView title, scheduleTitle;
	GridView calendar;
	Calendar mThisMonthCalendar;
	LinearLayout linear = null;
	DAO dao;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView() - month");
		View root = inflater.inflate(R.layout.monthcalendar, container, false);

		ImageButton bPrevMonth = (ImageButton) root.findViewById(R.id.prev);
		ImageButton bNextMonth = (ImageButton) root.findViewById(R.id.next);
		
		title = (TextView) root.findViewById(R.id.title);
		calendar = (GridView) root.findViewById(R.id.calendar);
		
		mDayList = new ArrayList<DayInfo>();

		mThisMonthCalendar = Calendar.getInstance();
		mThisMonthCalendar.set(Calendar.DAY_OF_MONTH, 1);
		getCalendar(mThisMonthCalendar);
		
		//다음달, 이전달 버튼
		bPrevMonth.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mThisMonthCalendar = getLastMonth(mThisMonthCalendar);
				getCalendar(mThisMonthCalendar);
			}
		});

		bNextMonth.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mThisMonthCalendar = getNextMonth(mThisMonthCalendar);
				getCalendar(mThisMonthCalendar);
			}
		});


		
		//날짜를 클릭했을때 등록
		calendar.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				SharedPreferences pref = getActivity().getSharedPreferences("date", 0);
				SharedPreferences.Editor edit = pref.edit();
				edit.putInt("year", mDayList.get(position).getYear());
				edit.putInt("month", mDayList.get(position).getMonth());
				edit.putInt("day", mDayList.get(position).getDay());
				edit.commit();
					
				linear = (LinearLayout) View.inflate(getActivity(), R.layout.todayschedulelist, null);
				
				final int year = mDayList.get(position).getYear();
				final int month = mDayList.get(position).getMonth();
				final int day = mDayList.get(position).getDay();	
				final String stime = String.format("%4d년 %d월 %d일", year, month, day);
				currentDate = String.format("%4d/%d/%d", year, month, day);
				
				Log.d(TAG, currentDate);
				
				//쿼리 결과. 해당날짜에 대한 스케쥴 목록 리스트
				dao = DAO.open(getActivity());
				//arList = dao.selectTodayScheduleFromDate(currentDate);
							
				//날짜를 선택하면 다이얼로그에 linear를 전개.
				tlAdapter = new TodayListAdapter(getActivity(), arList, R.layout.todayschedulelistlayout);
				ListView todayList = (ListView) linear.findViewById(R.id.todaylistview);
				todayList.setAdapter(tlAdapter);
								
				//스케쥴일 있는날과 스케쥴이 없는날 ListView에 다르게 출력
				if(arList.size() == 0){
					new AlertDialog.Builder(getActivity())
					.setTitle(stime)
					.setMessage("등록된 일정이 없음")
					.setPositiveButton("일정을 추가하려면 여기 클릭!", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
								
						}
						
					}).show();
					

				} else {
					new AlertDialog.Builder(getActivity())
					.setTitle(stime)
					.setView(linear)
					.setPositiveButton("일정을 추가하려면 여기 클릭!", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
						}
						
					}).show();
					
				}
				 
				//스케쥴이 있는날짜의 다이얼로그 ListView에 출력된 스케쥴을 클릭시 해당 스케쥴이 나오는 Deatil.class로 이동
				todayList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> adapterView, View clickedView, int pos, long id) {
						
					}
					
				});
				
			}
		});

		
		
		return root;
	}
		
	//캘린더 모양, 날짜 계산
	private void getCalendar(Calendar calendar) {
		int prevMonthStartDay;
		int dayOfMonth;
		int thisMonthLastDay;
		DayInfo day;
        
		mDayList.clear();

		// 이번달 시작일의 요일을 구한다. 시작일이 일요일인 경우 인덱스를 1(일요일)에서 8(다음주 일요일)로 바꾼다.
		dayOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
		thisMonthLastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		calendar.add(Calendar.MONTH, -1);

		// 지난달의 마지막 일자를 구한다.
		prevMonthStartDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		calendar.add(Calendar.MONTH, 1);

		if (dayOfMonth == SUNDAY) {
			dayOfMonth += 7;
		}

		prevMonthStartDay -= (dayOfMonth - 1) - 1;

		//오늘의 날짜를 반환
		title.setText(mThisMonthCalendar.get(Calendar.YEAR) + "년 " + (mThisMonthCalendar.get(Calendar.MONTH) + 1) + "월");

		//
		for (int i = 0; i < dayOfMonth - 1; i++) {
			int date = prevMonthStartDay + i;
			day = new DayInfo();
			day.setDay(date);
			day.setInMonth(false);
			day.setMonth(mThisMonthCalendar.get(Calendar.MONTH));
			day.setYear(mThisMonthCalendar.get(Calendar.YEAR) - 1);
			mDayList.add(day);
		}

		//달의 마지막일을 반환
		for (int i = 1; i <= thisMonthLastDay; i++) {
			day = new DayInfo();
			day.setDay(i);
			day.setInMonth(true);
			day.setMonth(mThisMonthCalendar.get(Calendar.MONTH) + 1);
			day.setYear(mThisMonthCalendar.get(Calendar.YEAR));
			mDayList.add(day);
		}

		for (int i = 1; i < 42 - (thisMonthLastDay + dayOfMonth - 1) + 1; i++) {
			day = new DayInfo();
			day.setDay(i);
			day.setInMonth(false);
			day.setMonth(mThisMonthCalendar.get(Calendar.MONTH) + 2);
			day.setYear(mThisMonthCalendar.get(Calendar.YEAR) + 1);
			mDayList.add(day);
		}

		initCalendarAdapter();
	}

	//이전달 계산
	private Calendar getLastMonth(Calendar calendar) {
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
		calendar.add(Calendar.MONTH, -1);
		title.setText(mThisMonthCalendar.get(Calendar.YEAR) + "년 " + (mThisMonthCalendar.get(Calendar.MONTH) + 1) + "월");
		return calendar;
	}

	//다음달 계산
	private Calendar getNextMonth(Calendar calendar) {
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
		calendar.add(Calendar.MONTH, +1);
		title.setText(mThisMonthCalendar.get(Calendar.YEAR) + "년 " + (mThisMonthCalendar.get(Calendar.MONTH) + 1) + "월");
		return calendar;
	}

	//그리드뷰에 전개할 날짜들의 레이아웃을 어댑터에 전개
	private void initCalendarAdapter() {
		mCalendarAdapter = new MonthCalendarAdapter(getActivity(), R.layout.monthday, mDayList);
		calendar.setAdapter(mCalendarAdapter);
	}
		
}